import { useState, useEffect } from 'react'
import {
  Card,
  Grid,
  Badge,
  Descriptions,
  Progress,
  Space,
  Tag,
  Button,
  Typography,
  Message,
  Divider,
} from '@arco-design/web-react'
import { IconPlus, IconRefresh, IconEye } from '@arco-design/web-react/icon'
import { getOnlineNodes, getNodeStatistics } from '@/api/node'
import type { NodeStatus, NodeStatistics } from '@/types'
import NodeRegistrationTokenModal from '@/components/NodeRegistrationTokenModal'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import './index.css'

dayjs.extend(relativeTime)

const { Row, Col } = Grid
const { Title, Text } = Typography

// 获取使用率状态
const getUsageStatus = (usage: number) => {
  if (usage >= 80) return 'error'
  if (usage >= 60) return 'warning'
  return 'success'
}

export default function NodePage() {
  const [loading, setLoading] = useState(false)
  const [nodes, setNodes] = useState<NodeStatus[]>([])
  const [statistics, setStatistics] = useState<NodeStatistics | null>(null)
  const [tokenModalVisible, setTokenModalVisible] = useState(false)

  // 加载节点列表
  const loadNodes = async () => {
    setLoading(true)
    try {
      const [nodesData, statsData] = await Promise.all([
        getOnlineNodes(),
        getNodeStatistics(),
      ])
      setNodes(nodesData)
      setStatistics(statsData)
    } catch (error) {
      console.error('Failed to load nodes:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadNodes()

    // 每 10 秒自动刷新
    const timer = setInterval(loadNodes, 10000)
    return () => clearInterval(timer)
  }, [])

  return (
    <div className="node-page">
      <div className="node-header">
        <Title heading={4}>节点管理</Title>
        <Space>
          <Button
            type="primary"
            icon={<IconPlus />}
            onClick={() => setTokenModalVisible(true)}>
            生成注册令牌
          </Button>
          <Button icon={<IconRefresh />} onClick={loadNodes} loading={loading}>
            刷新
          </Button>
        </Space>
      </div>

      {/* 统计信息 */}
      {statistics && (
        <Row gutter={16} style={{ marginBottom: 20 }}>
          <Col span={6}>
            <Card>
              <div className="stat-card">
                <Text type="secondary">总节点数</Text>
                <Title heading={3}>{statistics.totalNodes}</Title>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="stat-card">
                <Text type="secondary">在线节点</Text>
                <Title heading={3} style={{ color: 'var(--color-success-6)' }}>
                  {statistics.onlineNodes}
                </Title>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="stat-card">
                <Text type="secondary">离线节点</Text>
                <Title heading={3} style={{ color: 'var(--color-danger-6)' }}>
                  {statistics.offlineNodes}
                </Title>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="stat-card">
                <Text type="secondary">容量使用率</Text>
                <Title heading={3}>
                  {statistics.totalCapacity > 0
                    ? Math.round(
                        (statistics.usedCapacity / statistics.totalCapacity) *
                          100
                      )
                    : 0}
                  %
                </Title>
              </div>
            </Card>
          </Col>
        </Row>
      )}

      {/* 节点列表 */}
      <Row gutter={16}>
        {nodes.map((node) => (
          <Col span={8} key={node.nodeId}>
            <Card
              title={
                <Space>
                  <Badge status="success" />
                  <strong>{node.nodeName}</strong>
                </Space>
              }
              extra={
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {node.ipAddress}:{node.port}
                </Text>
              }
              style={{ marginBottom: 16 }}>
              <Descriptions
                column={1}
                size="small"
                colon=" :"
                data={[
                  {
                    label: '节点 ID',
                    value: (
                      <Text code style={{ fontSize: 11 }}>
                        {node.nodeId}
                      </Text>
                    ),
                  },
                  {
                    label: 'CPU 使用率',
                    value: (
                      <Progress
                        percent={node.cpuUsage}
                        status={getUsageStatus(node.cpuUsage)}
                        size="small"
                      />
                    ),
                  },
                  {
                    label: '内存使用率',
                    value: (
                      <Progress
                        percent={node.memoryUsage}
                        status={getUsageStatus(node.memoryUsage)}
                        size="small"
                      />
                    ),
                  },
                  ...(node.diskUsage !== undefined
                    ? [
                        {
                          label: '磁盘使用率',
                          value: (
                            <Progress
                              percent={node.diskUsage}
                              status={getUsageStatus(node.diskUsage)}
                              size="small"
                            />
                          ),
                        },
                      ]
                    : []),
                  {
                    label: '运行任务',
                    value: <Tag color="arcoblue">{node.runningTasks} 个</Tag>,
                  },
                  {
                    label: '支持环境',
                    value: (
                      <Space wrap>
                        {node.capabilities.map((cap) => (
                          <Tag key={cap} size="small">
                            {cap}
                          </Tag>
                        ))}
                      </Space>
                    ),
                  },
                  {
                    label: '最后心跳',
                    value: (
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {dayjs(node.lastHeartbeat).fromNow()}
                      </Text>
                    ),
                  },
                ]}
              />

              <Divider style={{ margin: '12px 0' }} />

              <Space>
                <Button
                  type="text"
                  size="small"
                  icon={<IconEye />}
                  onClick={() => Message.info('查看详情功能开发中...')}>
                  查看任务
                </Button>
              </Space>
            </Card>
          </Col>
        ))}
      </Row>

      {nodes.length === 0 && !loading && (
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Text type="secondary">暂无在线节点</Text>
          </div>
        </Card>
      )}

      <NodeRegistrationTokenModal
        visible={tokenModalVisible}
        onCancel={() => setTokenModalVisible(false)}
        onSuccess={() => {
          setTokenModalVisible(false)
          Message.success('令牌已生成，可在节点设置中查看')
        }}
      />
    </div>
  )
}
